package com.example.scenictourback.controller;

import com.example.scenictourback.common.Result;
import com.example.scenictourback.dto.OrderDTO;
import com.example.scenictourback.dto.PaymentDTO;
import com.example.scenictourback.service.OrderService;
import com.example.scenictourback.service.PaymentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/payment")
public class PaymentController {
    
    @Autowired
    private PaymentService paymentService;
    
    @Autowired
    private OrderService orderService;
    
    /**
     * 创建支付
     */
    @PostMapping("/create")
    public Result<?> createPayment(@RequestBody PaymentDTO paymentDTO) {
        PaymentDTO createdPayment = paymentService.createPayment(paymentDTO);
        return Result.success("创建支付成功", createdPayment);
    }
    
    /**
     * 处理支付
     */
    @PostMapping("/pay")
    public Result<?> processPayment(@RequestBody Map<String, Object> paymentInfo) {
        Integer orderId = (Integer) paymentInfo.get("orderId");
        Integer paymentMethod = (Integer) paymentInfo.get("method"); // 支付方式 1-微信 2-支付宝
        
        try {
            // 创建支付记录并更新订单状态
            PaymentDTO payment = paymentService.processPayment(orderId, paymentMethod);
            
            // 更新订单状态为已支付(2)
            OrderDTO updatedOrder = orderService.updateOrderStatus(orderId, 2);
            
            Map<String, Object> result = new HashMap<>();
            result.put("payment", payment);
            result.put("order", updatedOrder);
            
            return Result.success("支付成功", result);
        } catch (Exception e) {
            return Result.error("支付失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取支付详情
     */
    @GetMapping("/{id}")
    public Result<?> getPaymentById(@PathVariable Integer id) {
        PaymentDTO payment = paymentService.getPaymentById(id);
        return Result.success(payment);
    }
    
    /**
     * 根据订单ID获取支付信息
     */
    @GetMapping("/order/{orderId}")
    public Result<?> getPaymentByOrderId(@PathVariable Integer orderId) {
        PaymentDTO payment = paymentService.getPaymentByOrderId(orderId);
        return Result.success(payment);
    }
} 